<!--  -->
<template>
  <div class="">
    <header-top></header-top>
    <!--  -->
    <el-table :data="shopList" border stripe>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left">
            <el-form-item label="店铺">
              <span>{{ props.row.name }}</span>
            </el-form-item>
            <el-form-item label="店铺 ID">
              <span>{{ props.row.id }}</span>
            </el-form-item>
            <el-form-item label="店铺地址">
              <span>{{ props.row.address }}</span>
            </el-form-item>
            <el-form-item label="店铺描述">
              <span>{{ props.row.description }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="店铺名称" align="center">
      </el-table-column>
      <el-table-column prop="address" label="店铺地址" align="center">
      </el-table-column>
      <el-table-column prop="description" label="店铺介绍" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.$index, scope.row)" size="small"
            >编辑</el-button
          >
          <el-button size="small" @click.stop="addFood(scope.row)"
            >添加食品</el-button
          >
          <el-button
            @click="handleDelete(scope.$index, scope.row)"
            type="warning"
            size="small"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="user-list-pagination">
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="offset + 1"
        :page-size="limit"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="修改店铺信息" :visible.sync="dialogFormVisible">
      <el-form :model="selectTable" :rules="rules" ref="submitForm">
        <el-form-item label="店铺名称" prop="name" label-width="100px">
          <el-input v-model="selectTable.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item prop="address" label="详细地址" label-width="100px">
          <el-autocomplete
            v-model="selectTable.address"
            :fetch-suggestions="querySearch"
            placeholder="请输入内容"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item prop="description" label="店铺介绍" label-width="100px">
          <el-input v-model="selectTable.description"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="联系电话" label-width="100px">
          <el-input v-model="selectTable.phone"></el-input>
        </el-form-item>
        <el-form-item label="店铺分类" label-width="100px">
          <el-cascader
            :options="categoryOptions"
            v-model="selectedCategory"
            change-on-select
          ></el-cascader>
        </el-form-item>
        <el-form-item label="上传图片" label-width="100px">
          <el-upload
            class="avatar-uploader"
            :action="baseUrl + 'v1/addimg/avatar'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="selectTable.image_path"
              :src="baseImgPath + selectTable.image_path"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('submitForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import Header from "../header/Header";
import {
  getRestaurantsCount,
  searchPlace,
  foodCategory,
  getRestaurantsList,
  updateShop,
  deleteResturant,
} from "../../api/api";
import { baseUrl, baseImgPath } from "../../config/env";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    "header-top": Header,
  },
  data() {
    //这里存放数据
    return {
      // 当前选择编辑的对象
      dialogFormVisible: false, // 编辑的表格是否可见
      selectTable: {},
      shopList: [],
      limit: 3,
      offset: 0,
      total: 0,
      rules: {
        name: {
          required: true,
          trigger: "blur",
          message: "不能为空!",
        },
        address: {
          required: true,
          trigger: "blur",
          message: "不能为空!",
        },
        description: {
          required: true,
          trigger: "blur",
          message: "不能为空!",
        },
        phone: {
          required: true,
          trigger: "blur",
          message: "不能为空!",
        },
      },
      baseUrl: baseUrl,
      baseImgPath: baseImgPath,
      categoryOptions: [],
      selectedCategory: [],
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    addFood: function (row) {
      this.$router.push({
        path: "addFoods",
        query: { restaurant_id: row.id }
      });
    },
    submitForm: function (submitFormName) {
      this.$refs[submitFormName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          try {
            this.selectTable.category = this.selectedCategory.join("/");
            const res = await updateShop(this.selectTable);
            if (res.status == 1) {
              this.$message({
                type: "success",
                message: "更新店铺信息成功",
              });
              this.getRestaurantsList();
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          } catch (err) {
            console.log("更新餐馆信息失败", err);
          }
        } else {
          return false;
        }
        console.log(valid);
      });
    },
    handleAvatarSuccess(res) {
      if (res.status == 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error("上传图片失败！");
      }
    },
    beforeAvatarUpload(file) {
      const isRightType =
        file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isRightType && isLt2M;
    },
    getCategories: async function () {
      let res = await foodCategory();
      res.forEach((item) => {
        if (item.sub_categories.length) {
          const addnew = {
            value: item.name,
            label: item.name,
            children: [],
          };
          item.sub_categories.forEach((subitem, index) => {
            if (index == 0) {
              return;
            }
            addnew.children.push({
              value: subitem.name,
              label: subitem.name,
            });
          });
          this.categoryOptions.push(addnew);
        }
      });
    },
    handleSelect: function (item) {
      console.log(item);
    },
    querySearch: async function (queryString, cb) {
      console.log(queryString);
      if (queryString) {
        let res = await searchPlace({ keyword: queryString });
        if (res instanceof Array) {
          res.map((v) => {
            v.value = v.address;
          });
          cb(res);
        }
      }
    },
    handleEdit: function (index, row) {
      console.log(row);
      this.dialogFormVisible = true;
      this.selectTable = row;
      this.selectedCategory = row.category.split("/");
    },
    handleDelete: async function (index, row) {
      try {
        const res = await deleteResturant(row.id);
        if (res.status == 1) {
          this.$message({
            type: "success",
            message: "删除店铺成功",
          });
          this.shopList.splice(index, 1);
        } else {
          throw new Error(res.message);
        }
      } catch (err) {
        this.$message({
          type: "error",
          message: err.message,
        });
        console.log("删除店铺失败");
      }
    },
    handleCurrentChange(val) {
      this.offset = val - 1;
      this.getUserListFunc();
    },
    getUserListFunc: async function () {
      let res = await getRestaurantsList({
        offset: this.limit * this.offset++,
        limit: this.limit,
      });
      this.shopList = res;
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  async mounted() {
    this.getUserListFunc();
    let res = await getRestaurantsCount();
    // console.log(res);
    // this.shopList = res;
    this.total = res.count;
    this.getCategories();
  },
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='less' scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>